<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="选择部门" prop="departId">
        <el-select v-model="schoolId" placeholder="请选择学校" @change="changeSchool" style="width: 180px;">
          <el-option v-for="item in schools" :key="item.id" :label="item.schoolName" :value="item.id" />
        </el-select>
        <el-select v-model="queryParams.departId" placeholder="请选择部门" style="width: 180px;">
          <el-option v-if="queryParams.departId === -1" :key="-1" :label="'无部门数据'" :value="-1" disabled />
          <el-option v-for="item in departs" :key="item.id" :label="item.departName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="专业名称" prop="majorName">
        <el-input v-model="queryParams.majorName" placeholder="请输入专业名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['td:major:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading" v-hasPermi="['td:major:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      :default-sort="{ prop: 'schoolName', order: 'descending' }" ref="tableRef">
      <el-table-column label="学校名称" align="center" prop="schoolName" style="width: 280px;" />
      <el-table-column label="部门名称" align="center" prop="departName" style="width: 280px;" />
      <el-table-column label="专业名称" align="center" prop="majorName" />
      <el-table-column label="创建时间" align="center" prop="createTime" sortable :formatter="dateFormatter"
        width="180px" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)" v-hasPermi="['td:major:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['td:major:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MajorForm ref="formRef" @success="getList" />

</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { useSystemStore } from '@/store/modules/system'
import { MajorApi, MarjorAndDepartNameVo } from '@/api/td/major'
import { SchoolApi, SchoolForSelectVO } from '@/api/td/school'
import { DepartmentApi, DepartmentForSelectVo } from '@/api/td/department'
import MajorForm from './MajorForm.vue'
/** 专业 列表 */
defineOptions({ name: 'Major' })
const systemStore = useSystemStore() // 系统状态库的实例
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const tableRef = ref()//表格的引用
const loading = ref(true) // 列表的加载中
const list = ref<MarjorAndDepartNameVo[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  departId: undefined as number | undefined,
  majorName: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const schoolId = ref(undefined)//学校的id
const schools = ref<SchoolForSelectVO[]>([])//学校的下拉列表数据
const departs = ref<DepartmentForSelectVo[]>([])//部门的下拉列表数据

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MajorApi.getMajorAndDepartNameRespVoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 监听系统状态库的版本号是否发生改变，如果发生改变，重新拉取渲染表格 **/
watch(
  () => systemStore.state.version,
  () => {
    getList()
    getSchoolsForSelect()
    if (schoolId.value) {
      getDepartmentForSelect(schoolId.value)
    }
  },
  { deep: true }
)

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  schoolId.value = undefined // 修正为使用 .
  tableRef.value.sort('schoolName', 'descending')
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MajorApi.deleteMajor(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MajorApi.exportMajor(queryParams)
    download.excel(data, '专业.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 改变学校时触发 **/
const changeSchool = async (selectedSchoolId: number) => {
  // 清空当前部门选择
  queryParams.departId = undefined
  // 获取并更新部门列表
  await getDepartmentForSelect(selectedSchoolId)
  // 只有当选择的学校未变化时才处理
  if (selectedSchoolId !== schoolId.value) return
  // 根据部门数据情况设置部门ID
  queryParams.departId = departs.value.length > 0 ? departs.value[0].id : -1
}

/** 获取学校的下拉列表**/
const getSchoolsForSelect = async () => {
  const data = await SchoolApi.getSchoolsForSelect();
  schools.value = data
}

/** 获取部门的下拉列表通过学校的id**/
const getDepartmentForSelect = async (schoolId: number) => {
  const data = await DepartmentApi.getDepartmentsBySchoolId(schoolId);
  departs.value = data
}

/** 初始化 **/
onMounted(() => {
  getList();
  getSchoolsForSelect();
  getDepartmentForSelect(1);
});

</script>
